<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="500px"
    align-center
    destroy-on-close
    draggable
    @close="closeDialog"
    style="max-width: 650px; min-width: 600px"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90px"
      style="width: 97%"
    >
      <!-- 只读状态显示遮罩 -->
      <div v-show="isReadonly" class="formCover"></div>

      <el-form-item label="序号" prop="seq">
        <el-input v-model="formData.seq" placeholder="请输入序号" clearable />
      </el-form-item>

      <el-form-item label="工作方向" prop="taskName">
        <el-input
          v-model="formData.taskName"
          placeholder="请输入工作方向"
          clearable
        />
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="开始日期" prop="planStartDate">
            <el-date-picker
              v-model="formData.planStartDate"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              clearable
              type="date"
              placeholder="请选择开始日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="planEndDate">
            <el-date-picker
              v-model="formData.planEndDate"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              clearable
              type="date"
              placeholder="请选择结束日期"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="formData.remarks"
          placeholder="请输入备注"
          type="textarea"
          show-word-limit
          :maxlength="255"
          :autosize="{ minRows: 3, maxRows: 4 }"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-show="!isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable"; // 引入
import { useRoute } from "vue-router";

const route = useRoute();

defineOptions({
  name: "AddWorkDirection",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const isReadonly = ref(false);
/** 弹窗显示隐藏 */
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal && props.title.includes("查看")) {
      isReadonly.value = true;
    } else {
      isReadonly.value = false;
    }
  }
);

/** 定义form信息 */
const rules = reactive({
  seq: [
    { required: true, message: "请输入序号", trigger: "blur" },
    { max: 20, message: "序号不能超过20个字符", trigger: "blur" },
  ],
  taskName: [
    { required: true, message: "请输入工作方向", trigger: "blur" },
    { max: 50, message: "工作方向不能超过50个字符", trigger: "blur" },
  ],
  planStartDate: [
    { required: true, message: "请选择开始日期", trigger: "change" },
    { validator: validateStartTime, trigger: "change" },
  ],
  planEndDate: [
    { required: true, message: "请选择结束日期", trigger: "change" },
    { validator: validateEndTime, trigger: "change" },
  ],
  remarks: [{ message: "请输入备注", trigger: "blur" }],
});

const formRef = ref(ElForm);
// taskType
const initForm = {
  taskType: 0,
  taskName: "",
  seq: "",
  planStartDate: "",
  planEndDate: "",
  remarks: "",
  id: "",
  keyworkId: route.query.id,
};
let formData = reactive(JSON.parse(JSON.stringify(initForm)));

/** 编辑赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        taskType,
        taskName,
        seq,
        planStartDate,
        planEndDate,
        remarks,
      } = newVal;
      Object.assign(formData, {
        id,
        taskType,
        taskName,
        seq,
        planStartDate,
        planEndDate,
        remarks,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  Object.assign(formData, { ...JSON.parse(JSON.stringify(initForm)) });
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: formData.id
          ? "/system/oakeyworktask/update"
          : "/system/oakeyworktask/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`${text}成功`);
      emit("reset-table", formData.id || "");
      closeDialog();
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

function validateEndTime(rule: any, value: string, callback: (a?: any) => {}) {
  if (formData.planStartDate && value < formData.planStartDate) {
    callback(new Error("结束日期不能小于开始日期"));
  } else {
    callback();
  }
}

function validateStartTime(
  rule: any,
  value: string,
  callback: (a?: any) => {}
) {
  if (formData.planEndDate && value > formData.planEndDate) {
    callback(new Error("开始日期不能大于结束日期"));
  } else {
    callback();
  }
}
</script>
<style lang="scss" scoped>
.el-form {
  position: relative;
  .formCover {
    position: absolute;
    top: 0;
    width: 100%;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 2000;
    cursor: default;
  }
}
</style>
